#pragma once
#include <queue>
#include <pthread.h>
#include <iostream>
#include <string>
#include <unistd.h>
#include "Task.hpp"
// 用懒汉模式实现单例模式

struct ThreadInfo
{
    pthread_t tid;
    std::string threadname;
};
const int threadcount = 5;
template <class T>
class ThreadPool
{

private:
    ThreadPool(int count = threadcount) : _tds(count)
    {
        pthread_mutex_init(&_mutex, nullptr);
        pthread_cond_init(&_cond, nullptr);
    }
    ThreadPool(const ThreadPool<T> &td) = delete;
    const ThreadPool<T> &operator=(const ThreadPool<T> &td) = delete;

public:
    static ThreadPool<T> *GetInstance(int num = threadcount)
    {
        if (_tp == nullptr)
        {
            pthread_mutex_lock(&_lock);
            if (_tp == nullptr)
            {
                _tp = new ThreadPool<T>(num);
                pthread_mutex_unlock(&_lock);
                std::cout << "create ThreadPool one" << std::endl;
            }
        }
        return _tp;
    }
    ~ThreadPool()
    {
        pthread_mutex_destroy(&_mutex);
        pthread_cond_destroy(&_cond);
        for (int i = 0; i < _tds.size(); i++)
        {
            pthread_join(_tds[i].tid, nullptr);
        }
    }
    void Lock()
    {
        pthread_mutex_lock(&_mutex);
    }
    void Unlock()
    {
        pthread_mutex_unlock(&_mutex);
    }
    void Push(const T &in)
    {
        Lock();
        _taskqueue.push(in);
        Unlock();
        pthread_cond_signal(&_cond);
    }
    void Pop(T *out)
    {
        Lock();
        while (_taskqueue.size() == 0)
        {
            pthread_cond_wait(&_cond, &_mutex);
        }
        *out = _taskqueue.front();
        _taskqueue.pop();
        Unlock();
    }
    std::string &Getname(pthread_t tid)
    {
        for (auto &ti : _tds)
        {
            if (ti.tid == tid)
            {
                return ti.threadname;
            }
        }
    }
    static void *Rountine(void *arg)
    {
        ThreadPool<T> *tp = static_cast<ThreadPool<T> *>(arg);
        string name = tp->Getname(pthread_self());
        Task task;
        while (true)
        {
            tp->Pop(&task);
            task();
            sleep(1);
        }
    }

    void Start()
    {
        int num = _tds.size();
        for (int i = 0; i < num; i++)
        {
            _tds[i].threadname = "thread-" + std::to_string(i);
            pthread_create(&_tds[i].tid, nullptr, Rountine, this);
        }
    }

private:
    queue<T> _taskqueue;
    vector<ThreadInfo> _tds;
    pthread_mutex_t _mutex;
    pthread_cond_t _cond;
    static ThreadPool<T> *_tp;
    static pthread_mutex_t _lock;
};

template <class T>
ThreadPool<T> *ThreadPool<T>::_tp = nullptr;

template <class T>
pthread_mutex_t ThreadPool<T>::_lock = PTHREAD_MUTEX_INITIALIZER;